package com.bilin.coin.common.base;


import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.LocaleList;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.arouter.utils.TextUtils;
import com.bilin.coin.App;
import com.bilin.coin.network.RetrofitConfig;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.R;
import com.bilin.coin.bean.UserInfo;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.SharedPreferencesUtils;
import com.trello.rxlifecycle2.components.support.RxFragment;

import java.util.Locale;

import butterknife.ButterKnife;


/**
 * Fragment的基础类
 */

public abstract class BaseFragment extends RxFragment {
    public Context mContext;

    /**
     * 初始化视图
     */
    protected abstract void initView(View view, Bundle savedInstanceState);

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 加载布局文件
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 状态栏颜色
     */
    private int mStatusBarColor = R.color.mainColorBg;
    /**
     * 透明度
     */
    private int mStatusBarAlpha = 0;

    private Toast mToast;

    /**
     * 头部布局文件
     */
    private LinearLayout parentLinearLayout;
    public TextView mTvTitle;
    ImageView mIvMenu;
    protected ImageView iv_back;
    //Toolbar mToolbar;
    TextView mTvMenu;
    private Activity mActivity;
    /**
     * 判断是否加载头部布局，true为加载，false反之。
     */
    private boolean mShowToolBar = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
        this.mActivity = (Activity) context;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (mContext == null) {
            this.mContext = activity;
            this.mActivity = activity;
        }
    }

    /**
     * 设置语言
     *
     * @param
     */
    public void languageSeting2(String language) {
        // 本地语言设置
        /*Locale myLocale = new Locale(language);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);*/
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        Locale locale = new Locale(language);
        config.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(locale);
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);
            mContext.createConfigurationContext(config);
            Locale.setDefault(locale);
        }
        resources.updateConfiguration(config, dm);


    }

    /**
     * 设置语言
     *
     * @param language
     */
    public void languageSetting(String language) {
        // 本地语言设置
        /*Locale myLocale = new Locale(language);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);*/
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        Locale locale = Locale.CHINESE;
        String lang = SharedPreferencesUtils.getInstance().getString("language", "");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(Locale.CHINESE);
            if (lang.equals("zh_rTW")) {
                localeList = new LocaleList(Locale.TAIWAN);
            } else if (lang.equals("en")) {
                localeList = new LocaleList(Locale.ENGLISH);
            } else if (lang.equals("ko-rKR")) {
                localeList = new LocaleList(Locale.KOREA);
            } else {

            }
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);
            mContext.createConfigurationContext(config);
            Locale.setDefault(locale);
        } else {
            if (lang.equals("zh_rTW")) {
                config.locale = Locale.TAIWAN;
            } else if (lang.equals("en")) {
                config.locale = Locale.ENGLISH;
            } else if (lang.equals("ko-rKR")) {
                config.locale = Locale.KOREA;
            } else {
                config.locale = locale;
            }
        }
        resources.updateConfiguration(config, dm);

    }

    /**
     * 设置头部布局
     *
     * @param layoutResID
     */
    public void initHeadView(@LayoutRes int layoutResID, ViewGroup container, LayoutInflater inflater) {

        //container.removeAllViews();
        parentLinearLayout = new LinearLayout(mActivity);
        parentLinearLayout.setOrientation(LinearLayout.VERTICAL);
        ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        parentLinearLayout.setLayoutParams(params);
        container.addView(parentLinearLayout);
        View inflate = inflater.inflate(layoutResID, parentLinearLayout, true);

        mTvTitle = inflate.findViewById(R.id.tv_title);
        //mToolbar = inflate.findViewById(R.id.toolbar);
        mIvMenu = inflate.findViewById(R.id.iv_menu);
        iv_back = inflate.findViewById(R.id.iv_back);
        mTvMenu = inflate.findViewById(R.id.tv_menu);

        MenuOnClickListener();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //跟随系统变化语言
        if (!SharedPreferencesUtils.getInstance().getString("language", "").equals("")) {
            languageSetting(SharedPreferencesUtils.getInstance().getString("language", ""));
        }
        if (mContext == null && getActivity() != null) {
            this.mContext = getActivity();
            this.mActivity = getActivity();
        }
        View inflate;
        if (isShowToolBar()) {
            initHeadView(R.layout.public_toolbar, container, inflater);
            if (parentLinearLayout != null) {
                ViewGroup parent = (ViewGroup) parentLinearLayout.getParent();
                if (null != parent) {
                    parent.removeView(parentLinearLayout);
                }
            }
            inflate = inflater.inflate(getLayoutId(), parentLinearLayout, true);
        } else {
            inflate = inflater.inflate(getLayoutId(), container, false);
        }
        //inflate.setPadding((int) DensityUtils.px2dp(mActivity, 2),0,(int) DensityUtils.px2dp(mActivity, 2),(int) DensityUtils.px2dp(mActivity, 2));
        //inflate.setBackground(getResources().getDrawable(R.drawable.main_bg));
        //沉浸式状态栏
        //StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.colorPrimaryDark), 0);
        ButterKnife.bind(this, inflate);
        initView(inflate, savedInstanceState);
        return inflate;
    }


    /**
     * 子类重新该方法可以改变是否显示状态栏
     *
     * @param
     */
    public boolean isShowToolBar() {
        return mShowToolBar;
        //return false;
    }

    public void MenuOnClickListener() {
        if (mIvMenu != null) {
            mIvMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setMenuOnClickListener();
                }
            });
        }

        if (mTvMenu != null) {
            mTvMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setMenuOnClickListener();
                }
            });
        }
    }

    /**
     * 子类重写该方法实现点击回调
     */
    public void setMenuOnClickListener() {

    }

    public void setMenu(CharSequence menuName) {
        if (mIvMenu != null && mTvMenu != null) {
            mIvMenu.setVisibility(View.GONE);
            mTvMenu.setVisibility(View.VISIBLE);
            mTvMenu.setText(menuName);
        }

    }

    public void setMenu(Drawable drawable) {
        if (mIvMenu != null && mTvMenu != null) {
            mIvMenu.setVisibility(View.VISIBLE);
            mTvMenu.setVisibility(View.GONE);
            mIvMenu.setImageDrawable(drawable);
        }
    }

    public void setMenu(int resId) {
        if (mIvMenu != null && mTvMenu != null) {
            mIvMenu.setVisibility(View.VISIBLE);
            mTvMenu.setVisibility(View.GONE);
            mIvMenu.setImageResource(resId);
        }
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(CharSequence title) {
        if (mTvTitle != null) {
            mTvTitle.setText(title);
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initData();
        //StatusBarUtil.setColor(getActivity(), getResources().getColor(getStatusBarColor()), getStatusBarAlpha());
        //StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.colorPrimaryDark), 0);
    }


    /**
     * 隐藏键盘
     */
    public void hideSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            View localView = getActivity().getCurrentFocus();
            if (localView != null && localView.getWindowToken() != null) {
                IBinder windowToken = localView.getWindowToken();
                inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
            }
        }
    }

    /**
     * 显示键盘
     */
    public void showSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            View localView = getActivity().getCurrentFocus();
            if (localView != null && localView.getWindowToken() != null) {
                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public int getStatusBarColor() {
        return mStatusBarColor;
    }

    public void setStatusBarColor(int statusBarColor) {
        this.mStatusBarColor = statusBarColor;
    }

    public int getStatusBarAlpha() {
        return mStatusBarAlpha;
    }

    public void setStatusBarAlpha(int statusBarAlpha) {
        this.mStatusBarAlpha = statusBarAlpha;
    }

    /**
     * 经典无参跳转
     *
     * @param path
     */
    public void baseStartActivity(String path) {
        ARouter.getInstance().build(path).navigation();
    }

    /**
     * 有参跳转
     *
     * @param path
     * @return
     */
    public Postcard baseStartActivityWith(String path) {
        return ARouter.getInstance().build(path);
    }

    /**
     * 带回调的跳转
     *
     * @param path
     * @param RequestCode
     */
    public void baseStartActivityForResult(String path, int RequestCode) {
        ARouter.getInstance().build(path).navigation((Activity) mContext, RequestCode);
    }

    /**
     * 提示框
     *
     * @param text
     */
    public void showToast(String text) {
      /*  TextView content;
        if (mToast == null) {
            mToast = new Toast(mContext);
            View inflate = View.inflate(mContext, R.layout.toast, null);
            content = inflate.findViewById(R.id.tv_toast);
            mToast.setView(inflate);
        } else {
            View mToastView = mToast.getView();
            content = mToastView.findViewById(R.id.tv_toast);
        }
        mToast.setDuration(Toast.LENGTH_SHORT);
        content.setText("      "+text+"      ");
        mToast.show();*/
//        Toasty.Config.getInstance().setTextSize(14).allowQueue(false).apply();
//        Toasty.normal(mContext, text + "").show();
        //Toasty.normal(mContext, text).show();
        if (mContext != null)
            Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }


    /***
     * 网络请求后显示服务器返回的信息
     */
    protected void showMsg(Throwable e) {
        DialogUtils.dismissDialogLoading();
        Throwable cause = e.getCause();
        if (cause != null) {
            if (!TextUtils.isEmpty(cause.getMessage())) {
                showToast(cause.getMessage());
            } else {
                showToast("网络开小差了");
            }
        }
    }

    /**
     * 获取用户信息
     */
    /**
     * 获取用户信息
     */
    public void getSession() {
        RequestUtils
                .get()
                .url("/api/user/session")
                .build()
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        userInfoSession(null);
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        UserInfo userInfo = RequestUtils.getGson().fromJson(dataJson, UserInfo.class);
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, dataJson);
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile, userInfo.getMobile());
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord, userInfo.isHasSafeWord());
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.KYC_STATUS, userInfo.getKycStatus());
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin, userInfo.isLogin());
                        userInfoSession(userInfo);
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        userInfoSession(null);
                    }
                });
    }

    public void userInfoSession(UserInfo userInfo) {

    }

    protected void jumpArticle(String id, String title) {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", RetrofitConfig.newsUrl + id)
                .withString("title", title).navigation();
    }

}
